import express from 'express'
import multer from 'multer'
import fs from 'fs'
import path from 'path'
import cors from 'cors'

const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    // 切片存储的目录
    cb(null, 'uploads/')
  },
  filename: (req, file, cb) => {
    // 文件的名称
    cb(null, `${req.body.index}-${req.body.filename}`)
  }
})

const upload = multer({storage})

const app = express()
app.use(cors())
app.use(express.json())

app.post('/upload',upload.single('file'),(req,res) => {
  res.send('ok')
})

app.post('/merge',(req,res) => {
  const uploadDir = path.join(process.cwd(),'uploads')
  const dirs = fs.readdirSync(uploadDir)
  
  // 排序
  dirs.sort((a,b) => {
    return a.split('-')[0] - b.split('-')[0]
  })
  console.log(dirs);
  const video = path.join(process.cwd(),'video',`${req.body.fileName}.mp4`)
  dirs.forEach(item => {
    fs.appendFileSync(video,fs.readFileSync(path.join(uploadDir,item)))
    fs.unlinkSync(path.join(uploadDir,item))
  })
})

app.listen(3000,() => {
  console.log('服务启动')
})